package com.jman.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jman.user.dao.UserDao;
import com.jman.user.domain.User;
import com.jman.user.dto.UserDTO;
import com.jman.user.dto.UserWithToken;
import com.jman.user.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements IUserService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public UserWithToken getUserByPhone(String phone) {
        User user = query().eq("phone", phone).one();
        //用户查询为空则返回空
        if (user != null){
            log.debug("user查询成功");
            UserWithToken userWithToken = new UserWithToken();
            String token = saveWithToken(user);
            userWithToken.setUser(user);
            userWithToken.setToken(token);
            return userWithToken;
        }
        return null;
    }

    @Transactional
    public UserWithToken saveUser(String phone, String password) {
        User user = new User();
        user.setPhone(phone);
        user.setPassword(password);
        user.setNickName("User_" + RandomUtil.randomString(10));
        if (save(user)) {
            //用户已经存入数据库,id已经自动生成，重新取出user对象
            User lastUser = lambdaQuery().eq(User::getPhone, phone).one();
            String token = saveWithToken(lastUser);
            UserWithToken userWithToken = new UserWithToken();
            userWithToken.setUser(lastUser);
            userWithToken.setToken(token);
            return userWithToken;
        }
        return null;
    }

    /*将信息用户的部分信息存入redis中, 将所有键值都设为String类型*/
    private String saveWithToken(User user) {
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        Map<String, Object> userMap = BeanUtil.beanToMap(userDTO, new HashMap<>(),
                CopyOptions.create().setIgnoreNullValue(true).setFieldValueEditor((fieldName, fieldValue)
                        -> fieldValue.toString()));
        //生成token
        String token = UUID.randomUUID().toString(true);
        String userKey = "login:user:" + token;
        stringRedisTemplate.opsForHash().putAll(userKey, userMap);
        stringRedisTemplate.expire(userKey, 15, TimeUnit.MINUTES);
        return token;
    }


}
